package com.jolink.omiis.wechat.util;

import java.io.File;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * 
 * sftp-util
 * 
 * @author WangYanqing
 *
 */
public class SFTPUtil {

	private static Logger logger = LoggerFactory.getLogger(SFTPUtil.class);

	private static ChannelSftp createChannel() {
		long t1 = System.currentTimeMillis();
		String user = WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_UPLOAD_USER");
		String host = WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_UPLOAD_HOST");
		String password = WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_UPLOAD_PASSWORD");
		logger.info("创建SFTP通道，SFTP认证信息，user：{}，host：{}，password：{}", user, host, password);
		Session session = null;
		ChannelSftp sftp = null;
		JSch jsch = new JSch();
		try {
			session = jsch.getSession(user, host);
			logger.info("创建Session成功。");
			session.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			session.setConfig(sshConfig);
			session.connect();
			logger.info("Session连接成功。");
			Channel channel = session.openChannel("sftp");
			channel.connect();
			logger.info("获取Channel成功。");
			sftp = (ChannelSftp) channel;
		} catch (JSchException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		long t2 = System.currentTimeMillis();
		logger.info("创建sftp通道完成，耗时：{}毫秒。", (t2 - t1));
		return sftp;
	}

	public static boolean put(String src, String dst) {
		long t1 = System.currentTimeMillis();
		logger.info("通过SFTP上传文件，源文件：{}，目标路径：{}。", src, dst);
		ChannelSftp sftp = null;
		try {
			sftp = createChannel();
			try {
				sftp.cd(dst);
			} catch (Exception e) {
				logger.error("切换目录异常：" + e.getMessage(), e);
				sftp.mkdir(dst);
				sftp.cd(dst);
			}
			File file = new File(src);
			if (!file.exists()) {
				throw new RuntimeException("源文件不存在！");
			}
			sftp.put(src, file.getName());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return Boolean.FALSE;
		} finally {
			if (sftp.isConnected() || !sftp.isClosed()) {
				try {
					sftp.disconnect();
					sftp.getSession().disconnect();
				} catch (JSchException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("上传媒体文件耗时：{}毫秒。", (t2 - t1));
		return Boolean.TRUE;
	}
}
